<?php

namespace App\Service;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use  Darabonba\OpenApi\Models\Config;

class MobileSmsService extends BaseService
{

    public function createClient()
    {

        $accessKeyId = env('ALY_SMS_KEY','LTAI5tKN175h4xGHUdJ9q54W');
        $accessKeySecret = env('ALY_SMS_SECRET','IVqTZQvaK7hkFng3ynGse4xOkqmsbk');

        $config = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }


    /**
     * 发送短信
     * @param $phone string 手机号
     * @param $templateCode string 手机号模板
     * @param $templateParam array 参数
     * @param $signName string 签名
     * @return bool
     */
    public function send($phone,$templateCode='SMS_462020058',$templateParam = [],$signName = '聆听者')
    {

        $client = $this->createClient();
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $phone,
            "signName" => $signName,
            'templateCode' => $templateCode,
            'templateParam' => json_encode(['code' => 123456])
        ]);

        try {
            // 复制代码运行请自行打印 API 的返回值
            $result = $client->sendSmsWithOptions($sendSmsRequest, new RuntimeOptions([]));
            $result = $result->toMap();
            if (isset($result['statusCode']) && $result['statusCode'] == 200){
                return  true;
            }

        } catch (\Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }

        }
        return  false;

    }

}